package com.chujian.Activities;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;













import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chujian.Adapter.YiXuanAdapter;
import com.chujian.Global.Global;
import com.chujian.Threads.HttpClientPostThread;
import com.chujian.Utils.Constan;
import com.chujian.Utils.Util;
import com.chujian.model.Food;
import com.chujian.model.FoodList;
import com.chujian.model.ItemBean;
import com.chujian.model.Order;
import com.chujian.orderingsystem.R;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
/**
 *已选菜品，相当于购物车的功能
 * @author 周映凯
 *
 */
public class YixuanCaipinActivity extends Activity implements OnClickListener{
	private TextView tvTotalPrice;
	private Button btnClear;
	private Button btnSubmit;
	private String newAddOrder;
	private List<ItemBean> dataList;
	private ListView listView;
	private YiXuanAdapter myAdapter;
//	订单
	private Order mOrder;
	private List<FoodList>mList=new ArrayList<FoodList>();
	
	private Handler mHandler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			String str=(String)msg.obj;
			if(str.equals("FoodAddSuccess")){
				Util.confirmDialog("提示","添加成功",YixuanCaipinActivity.this);
				Intent intent=new Intent();
				intent.putExtra("newAddOrder", newAddOrder);
				setResult(3001, intent);
				clearData();
				finish();
			}else if(str.equals("FoodAddFailed")){
				Util.confirmDialog("提示","添加失败",YixuanCaipinActivity.this);
			}else {
				Toast.makeText(YixuanCaipinActivity.this, "订单提交成功", Toast.LENGTH_SHORT).show();
				Intent intent=new Intent(YixuanCaipinActivity.this, OrderCurrentDetailConsumerActivity.class);
				intent.putExtra("orderJson", str);
				startActivity(intent);
				clearData();
				YixuanCaipinActivity.this.finish();
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_yixuan_caipin);
//		listFood=(ArrayList<Food>) getIntent().getSerializableExtra("listFood");
		tvTotalPrice=(TextView) findViewById(R.id.tv_total_price);
		btnClear=(Button) findViewById(R.id.btn_clear);
		btnSubmit=(Button) findViewById(R.id.btn_submit);
		btnClear.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		
		listView=(ListView) findViewById(R.id.lv_yi_xuan);
		dataList=new ArrayList<ItemBean>();
		Iterator iter = Global.selectedFood.entrySet().iterator();
		Global.tatalPrice=0f;
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Food key = (Food) entry.getKey();
			Integer val = (Integer) entry.getValue();
			dataList.add(new ItemBean(key, val));
			Global.tatalPrice+=key.getFoodPrice()*val;
		}
		tvTotalPrice.setText("合计："+Global.tatalPrice+"元");
		myAdapter=new YiXuanAdapter(this, dataList, tvTotalPrice);
		listView.setAdapter(myAdapter);
		
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.btn_clear:
			if(dataList.isEmpty()){
				YixuanCaipinActivity.this.finish();
			}else{
				
				confirmDialog();
			}
			
			break;
		case R.id.btn_submit:
			String url=Constan.BASE_URL+"OrderServlet";
			String jsonString="这里是测试的json串";
			
//			FoodList foodlist=null;
			mList.clear();//防止多次点击的情况
			Iterator iter = Global.selectedFood.entrySet().iterator();
			Global.tatalPrice=0f;
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				Food key = (Food) entry.getKey();
				Integer val = (Integer) entry.getValue();
				Global.tatalPrice+=key.getFoodPrice()*val;
				mList.add(new FoodList(key.getFoodName(), val,key.getFoodPrice()));
			}
			if(Global.add_food_flag==true){
//				加菜模式
				mOrder=new Order("", "", Global.tatalPrice, mList);
				mOrder.setOrderId(Global.orderAddId);
				url=Constan.BASE_URL+"FoodListAddServlet";
			}else{
//				正常模式
				mOrder=new Order(Global.selectedTable,Global.loginUser.getUserPhone(), Global.tatalPrice, mList);
			}
			Gson gson=new Gson();
			String listJson=gson.toJson(mOrder);
			newAddOrder=listJson;
			new HttpClientPostThread(url, mHandler, listJson).start();;
			
			break;
		}
	}

	private void confirmDialog() {
		// TODO Auto-generated method stub
		 //    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
        AlertDialog.Builder builder = new AlertDialog.Builder(YixuanCaipinActivity.this);
        //    设置Title的图标
//        builder.setIcon(R.drawable.ic_launcher);
        //    设置Title的内容
        builder.setTitle("弹出警告框");
        //    设置Content来显示一个信息
        builder.setMessage("确定清除吗？");
        //    设置一个PositiveButton
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
            	
            	clearData();
    			tvTotalPrice.setText("合计："+Global.tatalPrice+"元");
    			myAdapter.notifyDataSetChanged();
    			YixuanCaipinActivity.this.finish();
            	
            }
        });
        //    设置一个NegativeButton
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
            	
            }
        });
        //    设置一个NeutralButton
/*        
        builder.setNeutralButton("忽略", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
            }
        });
*/        
        //    显示出该对话框
        builder.show();
	}

	public void clearData(){
		dataList.clear();
		Global.selectedFood.clear();
		Global.tatalPrice=0f;
		Global.count=0;
	}
	public void IbBack(View v){
		finish();
	}
	
}
